// miniprogram/pages/me/me.js
const app = getApp();
const cred = require('../../utils/credentials');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      type: Object,
      value: {}
    },
    isBusy: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getTabBar().update();
    this.setData({
      isBusy: false
    });
    if (cred.isAuthorized()) {
      this.setData({
        userInfo: cred.getCachedUserInfo() || {}
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      if (!this.data.userInfo.hasOwnProperty['nickName']) {
        if (cred.isAuthorized() && !this.data.isBusy) {
          this.setData({
            userInfo: cred.getCachedUserInfo() || {}
          });
        }
      }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  login: function () {
    console.log('login');
    this.setData({
      isBusy: true
    });
    cred.getUserInfo().then(info => {
      this.setData({
        userInfo: info
      });
    }).catch(e => console.log(e)).finally(() => {
      this.setData({
        isBusy: false
      });
    });
  }
})